package com.huaxindata.common.http;

import android.content.Context;
import android.os.Handler;
import android.os.Message;

import com.huaxindata.common.constants.HttpConstants;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * Created by Administrator on 2017/8/16.
 * 初始化okhttpClient的地方
 */

public class HxRetrofit {

    public static final String TAG = "HxRetrofit";
    private static Retrofit retrofit;
    private static OkHttpClient client;
    private static ListenerHandler listenerHandler;
    private static Context mContext;


    public static void clearCookie() {
        mCookies = null;
    }

    private static List<Cookie> mCookies;

    public static void init(Context context) {
        mContext = context;
        if (listenerHandler == null) {
            listenerHandler = new ListenerHandler();
        }
        if (client == null) {
            CookieJar cookieJar = new CookieJar() {
                @Override
                public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
                    if (url.toString().contains(HttpConstants.LOGIN_URL)) {
                        setCookies(cookies);
                    }
                }

                @Override
                public List<Cookie> loadForRequest(HttpUrl url) {
                    if (url.toString().contains(HttpConstants.BASE_URL)) {
                        List<Cookie> cookies = getCookies();
                        return cookies != null ? cookies : new ArrayList<Cookie>();
                    }
                    return new ArrayList<>();
                }
            };

            Interceptor downloadInterceptor = new Interceptor() {
                @Override
                public Response intercept(final Chain chain) throws IOException {
                    Response response = chain.proceed(chain.request());
                    //下载进度监听
                    return response.newBuilder()
                            .body(new ProgressResponseBody(response.body(), new ProgressListener() {
                                @Override
                                public void onProgress(long progress, long total, boolean done) {
                                    listenerHandler.obtainMessage(0, new MessageBean(chain
                                            .request().url(), progress, total, done))
                                            .sendToTarget();
                                }
                            }))
                            .build();
                }
            };
            client = new OkHttpClient.Builder()
                    .cookieJar(cookieJar)
                    .addNetworkInterceptor(downloadInterceptor)
                    .readTimeout(100, TimeUnit.SECONDS)//设置读取超时时间
                    .writeTimeout(100, TimeUnit.SECONDS)//设置写的超时时间
                    .connectTimeout(100, TimeUnit.SECONDS)//设置连接超时时间
                    .build();
        }
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(HttpConstants.BASE_URL)
                    //增加返回值为String及基本数据类型的支持
                    .addConverterFactory(ScalarsConverterFactory.create())
                    //增加返回值为Gson的支持(以实体类返回)
                    .addConverterFactory(GsonConverterFactory.create())
                    //增加返回值为Observable<T>的支持
//                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .client(client)
                    .build();

        }
    }
    public static Retrofit getInstance(){
        if (client != null) {
            return retrofit;
        } else {
            throw new RuntimeException("you must initial retrofit first by invoke init() method");
        }
    }
    public static List<Cookie> getCookies() {
        return mCookies;
    }

    public static void setCookies(List<Cookie> mCookies) {
        HxRetrofit.mCookies = mCookies;
    }
    public static class MessageBean {
        private HttpUrl mRequest;
        private long    mProgress;
        private long    mTotal;
        private boolean mDone;

        public MessageBean(HttpUrl request, long progress, long total, boolean done) {
            mRequest = request;
            mProgress = progress;
            mTotal = total;
            mDone = done;
        }

        public HttpUrl getRequest() {
            return mRequest;
        }

        public long getProgress() {
            return mProgress;
        }

        public long getTotal() {
            return mTotal;
        }

        public boolean isDone() {
            return mDone;
        }
    }

    public static class ListenerHandler extends Handler {

        private Map<HttpUrl, ProgressListener> listenerMap = new HashMap<>();

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            MessageBean mBean = (MessageBean) msg.obj;
            ProgressListener pListener = listenerMap.get(mBean.getRequest());
            if (pListener != null) {
                pListener.onProgress(mBean.getProgress(), mBean.getTotal(), mBean.isDone());
                if (mBean.isDone()) {
                    listenerMap.remove(mBean.getRequest());
                }
            }

        }

        public void addListener(HttpUrl call, ProgressListener progressListener) {
            listenerMap.put(call, progressListener);
        }

        public void reconnectListener(HttpUrl call, ProgressListener progressListener) {
            if (listenerMap.containsKey(call)) {
                listenerMap.put(call, progressListener);
            }
        }

    }
}
